<template>
  <div>
    <div class="crm-container">
      <el-tabs
        v-model="acitveTabValue"
        @tab-click="tabClick"
        style="padding: 0 16px;"
      >
        <el-tab-pane
          :label="item.name"
          :name="`${item.label}`"
          v-for="(item, index) in tableList"
          :key="index"
        >
        </el-tab-pane>
      </el-tabs>
      <div class="customer-content">
        <div class="d-flex flex-column">
          <!-- 月 -->
          <div class="column-box d-flex flex-column">
            <c-r-m-head
              ref="crmTableHead1"
              :crm-type="'monthStatis'"
              :table-class="true"
              @monthchange="changeMonth"
              @on-search="crmSearch(1)"
              @name="nameChange"
              title="渠道名称"
              placeholder="请选择渠道名称"
            >
            </c-r-m-head>
            <div class="column-box_picture">
              <div
                ref="overMonthChart"
                style="width: 100%; height: 350px"
                v-show="acitveTabValue == 'ROI统计'"
              ></div>
              <div
                ref="overMonthChart2"
                style="width: 100%; height: 350px"
                v-show="acitveTabValue == '客单价统计'"
              ></div>
            </div>
            <div class="column-box_statis">
              <!-- 表格区域  :loading="loading"-->
              <el-table
                :data="transData"
                border
                style="width: 100%;color: #666666; font-size: 14px;"
                :cell-style="{ 'text-align': 'center' }"
              >
                <el-table-column
                  v-for="(item, index) in transTitle"
                  :label="item.label"
                  :key="index"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row[index] }}
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-topText">
                <span>统计说明：</span>
                <span>{{
                  `${
                    acitveTabValue == "ROI统计"
                      ? "平均ROI=总回款金额÷总消耗"
                      : "平均客单价=总消耗÷总表单量"
                  }`
                }}</span>
                <span class="ml-20">{{
                  `${
                    acitveTabValue == "ROI统计"
                      ? "预期ROI=(已还清回款总额+还款中回款总额) ÷总消耗"
                      : ""
                  }`
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 表头组件
import CRMHead from "./components/CRMHead.vue";

import Table from "./mixins/table";
import initChart from "./mixins/initChart";

import {
  roiStatisForMonthAPI,
  roiStatisForYearAPI,
  priceStatisForYearAPI,
  priceStatisForMonthAPI
} from "@/api/roi";

export default {
  /** ROI统计(月/年) */
  name: "consume",
  mixins: [Table, initChart],
  data() {
    return {
      crmType: "statis",
      acitveTabValue: "ROI统计",
      tableList: [
        {
          label: "ROI统计",
          name: "ROI统计"
        },
        {
          label: "客单价统计",
          name: "客单价统计"
        }
      ],
      monthDays: [],
      month: "",
      putinPlatform: "",
      expectDayRoiList: [], // 预期ROI---月
      dayList: [],
      dayRoiList: [],
      expectRoiList: [], //预期ROI-----年
      yearMonthList: [], // 月份
      averageRoiList: [], // 平均ROI
      realityRoiList: [], // 实际ROI
      originTitle: [], //为表头展示数据 保证数组里每一个对象中的字段顺序, 从上到下 一次对应显示表格中的从左到右
      transData: [], // 月
      transDataYear: [], //年
      transTitle: [],
      transTitleYear: [],
      tableData: [],
      // --------------------
      dayListMonth: [], // 客单价---月
      priceList: [],
      priceTableList: [],
      currentVal: ""
    };
  },
  components: {
    CRMHead
  },
  computed: {},
  mounted() {
    this.initEchart("ROI统计");
    this.initEchartYear("ROI统计");
  },
  methods: {
    handleHandle() {},
    changeMonth(val) {
      this.month = "";
      this.month = val.month;
      this.currentVal = "1";
    },
    nameChange(val) {
      this.putinPlatform = "";
      this.putinPlatform = val.name;
      this.currentVal = "1";
    },
    nameChange1(val) {
      this.putinPlatform = val.name;
      this.currentVal = "2";
    },
    crmSearch(val) {
      if (val == 1) {
        this.month = this.$refs["crmTableHead1"].queryOptions.month;
        this.putinPlatform = this.$refs["crmTableHead1"].queryOptions.name;
        this.initEchart(this.acitveTabValue);
      } else {
        this.month = this.$refs["crmTableHead2"].queryOptions.name;
        this.putinPlatform = this.$refs["crmTableHead2"].queryOptions.name;
        this.initEchartYear(this.acitveTabValue);
      }
    },
    /** tab页签点击 */
    tabClick(tab) {
      this.month = "";
      this.putinPlatform = "";
      this.$refs["crmTableHead1"].clearForm();
      this.initEchart(this.acitveTabValue);
    },
    // 折线图
    initEchart(val) {
      if (val == "客单价统计") {
        // 月
        const paramsmonth = {
          month: this.month,
          putinPlatform: this.putinPlatform
        };
        priceStatisForMonthAPI(paramsmonth)
          .then(res => {
            this.dayListMonth = res.data.dayList; //日期
            this.priceList = res.data.priceList; //实际客单价
            this.priceTableList = res.data.priceTableList;
            let chart = this.$echarts.init(this.$refs.overMonthChart2);
            this.initMonthChart(
              res.data.dayList,
              "月度客单价",
              ["#86407F"],
              [res.data.priceList],
              ["平均客单价"],
              chart
            );
            this.dayListMonth.unshift("月度统计");
            this.priceList.unshift("客单价");
            this.transData = [];
            this.transData = [this.dayListMonth, this.priceList];
            this.putdata("客单价月");
          })
          .catch(() => {});
      } else {
        const params = {
          putinPlatform: this.putinPlatform,
          month: this.month
        };
        roiStatisForMonthAPI(params)
          .then(res => {
            this.expectDayRoiList = res.data.expectDayRoiList;
            this.dayList = res.data.dayList;
            this.dayRoiList = res.data.dayRoiList;
            this.roiTableList = res.data.roiTableList;
            let chart = this.$echarts.init(this.$refs.overMonthChart);
            this.initChart(
              res.data.dayList,
              "ROI月度统计",
              ["#5470C6", "#FA2F2F"],
              [res.data.expectDayRoiList, res.data.dayRoiList],
              ["平均ROI", "预期ROI"],
              chart
            );
            this.transData = [];
            this.transData = [
              this.expectDayRoiList,
              this.dayRoiList,
              this.dayList
            ];
            this.putdata("ROI统计月");
          })
          .catch(() => {});
      }
    },
    initEchartYear(val) {
      if (val == "客单价统计") {
        const params = {
          putinPlatform: this.putinPlatform
        };
        priceStatisForYearAPI(params)
          .then(res => {
            this.averagePriceList = res.data.averagePriceList; //平均客单价
            this.realityPriceList = res.data.realityPriceList; //实际客单价
            this.yearMonthList = res.data.yearMonthList; //月份
            let chart = this.$echarts.init(this.$refs.overYearChart2);
            this.initChart(
              res.data.dayList,
              "年度客单价（近一年）",
              ["#86407F", "#70A2FC"],
              [res.data.averagePriceList, res.data.realityPriceList],
              ["平均客单价", "实际客单价"],
              chart
            );
            // this.averagePriceList.unshift("平均客单价");
            // this.realityPriceList.unshift("实际客单价");
            // this.yearMonthList.unshift("年度统计");
            this.transDataYear = [];
            this.transDataYear = [
              this.averagePriceList,
              this.realityPriceList,
              this.yearMonthList
            ];
            this.putdata("客单价年");
          })
          .catch(() => {});
      } else {
        const yearparams = {
          putinPlatform: this.putinPlatform
        };
        roiStatisForYearAPI(yearparams)
          .then(res => {
            this.expectRoiList = res.data.expectRoiList; //预期ROI
            this.yearMonthList = res.data.yearMonthList;
            this.averageRoiList = res.data.averageRoiList;
            this.realityRoiList = res.data.realityRoiList;
            let yearChart = this.$echarts.init(this.$refs.overYearChart);
            this.initYearChart(
              this.yearMonthList,
              "ROI年度统计",
              ["#5470C6", "#94CE79", "#FA2F2F"],
              [this.averageRoiList, this.realityRoiList, this.expectRoiList],
              ["平均ROI", "实际ROI", "预期ROI"],
              yearChart
            );
            // this.yearMonthList1 = res.data.yearMonthList.unshift('年度统计')
            // this.averageRoiList1 = res.data.averageRoiList.unshift('平均ROI');
            // this.realityRoiList1 =res.data.realityRoiList.unshift('实际ROI');
            // this.expectRoiList1 = res.data.expectRoiList.unshift('预期ROI');
            // this.transDataYear = [];
            // this.transDataYear = [
            //   this.yearMonthList,
            //   this.averageRoiList,
            //   this.realityRoiList,
            //   this.expectRoiList
            // ];
            this.putdata("ROI统计年");
          })
          .catch(() => {});
      }
    },
    putdata(val) {
      this.tableData = [];
      if (val == "客单价月") {
        // this.tableData = [];
        // this.tableData = this.priceTableList;
        // this.originTitle = [];
        // this.originTitle = ["月度统计", "客单价"];
        // if (this.tableData.length > 0) {
        //   let matrixData = this.tableData.map(row => {
        //     let arr = [];
        //     for (let key in row) {
        //       arr.push(row[key]);
        //     }
        //     return arr;
        //   });
        //   if (matrixData.length > 0) {
        //     this.transData = matrixData[0].map((col, i) => {
        //       return [
        //         this.originTitle[i],
        //         ...matrixData.map(row => {
        //           return row[i];
        //         })
        //       ];
        //     });
        //     this.transTitle = matrixData.map((col, i) => {
        //       return [i + 1];
        //     });
        //     this.transTitle.unshift("");
        //   }
        // }
        // return;
      } else if (val == "ROI统计月") {
        this.tableData = [];
        this.tableData = this.roiTableList;
        this.originTitle = [];
        this.originTitle = ["月度统计", "平均ROI", "预期统计"];
        if (this.tableData.length > 0) {
          let matrixData = this.tableData.map(row => {
            let arr = [];
            for (let key in row) {
              if (key == "day") {
                arr[0] = row[key];
              } else if (key == "dayRoi") {
                arr[1] = row[key];
              } else if (key == "expectDayRoi") {
                arr[2] = row[key];
              }
            }
            return arr;
          });

          if (matrixData.length > 0) {
            this.transData = matrixData[0].map((col, i) => {
              return [
                this.originTitle[i],
                ...matrixData.map(row => {
                  return row[i];
                })
              ];
            });
            this.transTitle = matrixData.map((col, i) => {
              return [i + 1];
            });
            this.transTitle.unshift("");
          }
        }
        return;
      } else if (val == "ROI统计年") {
        let tableData1 = [];
        var arr = [];
        const expectRoiList = this.expectRoiList; // 预期
        const averageRoiList = this.averageRoiList; // 平均
        const realityRoiList = this.realityRoiList; // 实际
        const yearMonthList = this.yearMonthList; // 年度
        expectRoiList.forEach((item, index) => {
          arr.push({
            zero: item,
            one: averageRoiList[index],
            two: realityRoiList[index],
            thr: yearMonthList[index]
          });
        });
        tableData1 = arr;
        this.transTitleYear = [];
        this.transTitleYear = ["年度统计", "平均ROI", "实际ROI", "预期ROI"];
        if (tableData1.length > 0) {
          let matrixData = tableData1.map(row => {
            let arr = [];
            for (let key in row) {
              if (key == "thr") {
                arr[0] = row[key];
              } else if (key == "one") {
                arr[1] = row[key];
              } else if (key == "two") {
                arr[2] = row[key];
              } else if (key == "zero") {
                arr[3] = row[key];
              }
            }
            return arr;
          });
          if (matrixData.length > 0) {
            this.transDataYear = matrixData[0].map((col, i) => {
              return [
                this.transTitleYear[i],
                ...matrixData.map(row => {
                  return row[i];
                })
              ];
            });
            // 横向展示序号
            this.transTitleYear = matrixData.map((col, i) => {
              return [i + 1];
            });
            this.transTitleYear.unshift("");
          }
        }
        return;
      } else if (val == "客单价年") {
        this.tableData = [];
        this.tableData = this.priceTableList;
        var arr = [];
        const averagePriceList = this.averagePriceList;
        const realityPriceList = this.realityPriceList;
        const yearMonthList = this.yearMonthList;
        averagePriceList.forEach((item, index) => {
          arr.push({
            zero: yearMonthList[index],
            one: realityPriceList[index],
            two: item
          });
        });
        this.tableData = arr;
        this.transTitleYear = [];
        this.transTitleYear = ["年度统计", "平均客单价", "实际客单价"];
        if (this.tableData.length > 0) {
          let matrixData = this.tableData.map(row => {
            let arr = [];
            for (let key in row) {
              arr.push(row[key]);
            }
            return arr;
          });
          // 加入标题拼接最终的数据
          if (matrixData.length > 0) {
            this.transDataYear = matrixData[0].map((col, i) => {
              return [
                this.transTitleYear[i],
                ...matrixData.map(row => {
                  return row[i];
                })
              ];
            });
            this.transTitleYear = matrixData.map((col, i) => {
              return [i + 1];
            });
            this.transTitleYear.unshift("");
          }
        }
        return;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";
.crm-container {
  background-color: #fff;
  padding: 16px 0;
}
.table-head-container {
  padding: 14px 0;
}

.customer-content {
  .column-box {
    padding: 0 16px;
    &_picture {
      height: 403px;
      border: 1px solid #e5e5e5;
      padding: 24px;
    }
    &_statis {
      margin-top: 24px;
      // height: 200px;
      // border: 1px solid #e5e5e5;
    }
  }
  .col-box {
    margin: 16px 0;
    height: 15px;
    background-color: #f5f6f9;
  }
}

.table-topText {
  margin-bottom: 15px;
  height: 40px;
  line-height: 40px;
  span {
    font-size: 14px;
    color: #666;
    display: inline-block;
  }
}

/deep/ .has-gutter {
  display: none;
}
/deep/ .el-table__cell {
  border-right: 1px solid #e5e5e5 !important;
}
/deep/ .el-table__row {
  & td:first-child {
    color: #333;
    font-size: 14px;
    font-weight: bold !important;
  }
}
/deep/ tbody {
  & .el-table__row td {
    color: #333;
    font-size: 14px;
  }
}
/deep/ .el-table__body {
  & .el-table__row:nth-child(2) {
    color: #666 !important;
  }
}
</style>
